package com.scholarship.modules.login.controller;

import com.scholarship.common.entity.RetCode;
import com.scholarship.common.entity.RetResponse;
import com.scholarship.common.entity.RetResult;
import com.scholarship.modules.login.dto.LoginInfoDto;
import com.scholarship.modules.login.entity.User;
import com.scholarship.modules.login.exce.EmailException;
import com.scholarship.modules.login.service.LoginService;
import com.scholarship.modules.login.service.MailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Future;

@Api(tags = {"登录控制层"})
@RestController
public class LoginController {
    //日志logger
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    LoginService loginService;

    @Autowired
    MailService mailService;

    /**
     * 登录
     * @param userId    用户名
     * @param password  密码
     * @param rememberMe    记住我，默认为false
     * @return  登录身份或失败
     */
    //@CrossOrigin  用于解决跨域
    @ApiOperation("登录")
    @PostMapping("/login")
    public RetResult login(@RequestParam(value = "userId") String userId,
                           @RequestParam(value = "password") String password,
                           @RequestParam(value = "rememberMe",defaultValue = "false") Boolean rememberMe) throws Exception {
        try{
            String sessionId = loginService.login(userId,password,rememberMe);
            return RetResponse.makeRsp(RetCode.SUCCESS,"登录成功",sessionId);
        } catch (UnknownAccountException e) {
            return RetResponse.makeRsp(RetCode.USER_NOT_EXIST,"用户名不存在");
        } catch (IncorrectCredentialsException e) {
            return RetResponse.makeRsp(RetCode.ERROR_PWD,"密码错误");
        }
    }

    /**
     * 获取登录信息
     * @return
     */
    @ApiOperation("获取登录信息")
    @GetMapping("/info")
    public RetResult getLoginInfo() {
        try {
            Subject subject = SecurityUtils.getSubject();
            LoginInfoDto loginInfoDto = (LoginInfoDto) subject.getPrincipals().getPrimaryPrincipal();
            return RetResponse.makeOKRsp(loginInfoDto);
        } catch(Exception e) {
            return RetResponse.makeRsp(RetCode.FAIL,"未登录或会话过期");
        }
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public RetResult logout() {
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            return RetResponse.makeRsp(RetCode.SUCCESS,"退出成功");
        } catch (Exception e) {
            return RetResponse.makeRsp(RetCode.FAIL,"未登录");
        }
    }

    @ApiOperation("没有权限")
    @GetMapping("/noauth")
    public RetResult unauthorized() {
        return RetResponse.makeRsp(RetCode.FAIL,"未经授权无法访问");
    }

    @ApiOperation("给邮件发送验证码")
    @PostMapping("/send")
    public RetResult sendEmail(@RequestParam(value = "email") String email) {
        try {
            Future future = mailService.sendMail(email);

            if((Boolean) future.get()) {
                return RetResponse.makeOKRsp();
            }
            return RetResponse.makeRsp(RetCode.EMPTY_CONTENT,"该邮箱未绑定学号");
        } catch (Exception e) {
            logger.error(e.getMessage());
            return RetResponse.makeRsp(RetCode.FAIL,"发送失败，请联系客服");
        }
    }

    @ApiOperation("比对验证码")
    @PostMapping("/compare")
    public RetResult compareCode(@RequestParam(value = "email") String email,
                                 @RequestParam(value = "code") String code) {
        try {
            if(mailService.compareCode(email,code)) {
                return RetResponse.makeRsp(RetCode.SUCCESS,"匹配成功");
            }else {
                return RetResponse.makeRsp(RetCode.ERROR_PWD,"验证码错误");
            }

        }catch (Exception e) {
            logger.error(e.getMessage());
            return RetResponse.makeRsp(RetCode.FAIL,e.getLocalizedMessage());
        }
    }

    @ApiOperation("修改密码")
    @PostMapping("/change")
    public RetResult changePassword(@RequestParam(value = "email") String email,
                                    @RequestParam(value = "password") String password) {
        try {
            loginService.changePassword(email,password);
            return RetResponse.makeOKRsp();
        }catch(Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return RetResponse.makeRsp(RetCode.FAIL,e.getLocalizedMessage());
        }
    }
}
